package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static net.sf.jsqlparser.schema.Sequence.ParameterType.CACHE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryByid(Long id) {
        // 使用封装工具类的缓存穿透
      Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);

//        Shop shop = queryWithMutex(id);
//        if(shop == null){
//            return Result.fail("不存在");
//        }

        return Result.ok(shop);
    }

    // 互斥锁解决缓存击穿的问题,同时也解决了缓存穿透的问题
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 添加缓存功能
        // 先从redis中查，查到了直接返回，查不到再从数据库查，查到了写入redis并返回，查不到返回报错
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(s)){
            return BeanUtil.toBean(s, Shop.class);
        }

        // 应对缓存穿透的空缓存存入法
        if(s != null){
            return null;
        }

        String lockkey = "lock:shop:"+id;
        Shop shop = null;
        try {
            boolean islock = trylock(lockkey);

            // 获取锁成功以后进行二次检测
            String s2 = stringRedisTemplate.opsForValue().get(key);
            if(StrUtil.isNotBlank(s2)){
                return BeanUtil.toBean(s2, Shop.class);
            }

            if(! islock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            shop = getById(id);
            // 模拟key重建的延迟
            Thread.sleep(200);
            if(shop == null){
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_NULL_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockkey);
        }

        return shop;
    }

    // 解决缓存穿透问题
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 添加缓存功能
        // 先从redis中查，查到了直接返回，查不到再从数据库查，查到了写入redis并返回，查不到返回报错
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(s)){
            return BeanUtil.toBean(s, Shop.class);
        }

        // 应对缓存穿透的空缓存存入法
        if(s != null){
            return null;
        }

        Shop shop = getById(id);
        if(shop == null){
            // 写入空值是为了避免缓存击穿
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);

        return shop;
    }


    private boolean trylock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result updatebyid(Shop shop) {
        // 先更新数据库，再删除redis
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }

        updatebyid(shop);

        stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());

        return Result.ok();
    }

    // 分页查询商户
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否根据距离进行查询
        if(x == null || y == null){
            Page<Shop> page = query().eq("type_id",typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));

            return Result.ok(page.getRecords());
        }
        // 2.计算分页参数
        int from = (current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current*SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.如果是根据距离排序，那么查询redis，根据距离进行排序与分页    结果：shopid和距离
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(x, y), new Distance(5000), RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        // 4.得到了排序的id以后再去数据库里进行查找
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result->{
            String id = result.getContent().getName();
            ids.add(Long.valueOf(id));
            Distance distance = result.getDistance();
            distanceMap.put(id, distance);
        });

        String str = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + str + ")").list();

        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        return Result.ok(shops);
    }
}
